package LC;

/**
 * @author lhn
 * @date 2024-09-26 15:25
 * 14. 最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 */

public class LongestCommonPrefix {
    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower","flow","flight"}));
        System.out.println(longestCommonPrefix(new String[]{"dog","racecar","car"}));
        System.out.println(longestCommonPrefix(new String[]{"ab","a"}));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        String prefix = strs[0];    // 初始化
        for (int i = 1; i < strs.length; i++) {
//            System.out.println(prefix + " compare with " + strs[i] + " : " + commonPrefix(prefix, strs[i]));
            prefix = commonPrefix(prefix, strs[i]);
            if (prefix.equals("")) return "";   // 只要有一个为空，则返回空
        }
        return prefix;
    }

    public static String commonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < length) {
            if (str1.charAt(index) != str2.charAt(index)) {
                break;
            }
            index++;
        }
        return str1.substring(0, index);
    }
}
